import React, { useState, useEffect } from 'react';
import { 
  Box, 
  Typography, 
  Paper, 
  Grid, 
  Divider, 
  Button, 
  CircularProgress,
  Alert,
  TextField,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  FormGroup,
  FormControlLabel,
  Checkbox,
  Chip
} from '@mui/material';
import { 
  DirectionsCar, 
  Info, 
  CalendarToday, 
  ArrowBack,
  Save
} from '@mui/icons-material';
import { apiRequest } from '../utils/api';
import axios from 'axios';
import { useNavigate, useParams } from 'react-router-dom';

const VehicleEdit = () => {
  const { id } = useParams();
  const navigate = useNavigate();
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');
  const [currentUser, setCurrentUser] = useState(null);
  const [tagInput, setTagInput] = useState('');
  const [formData, setFormData] = useState({
    brand: '',
    model: '',
    color: '',
    year: '',
    licensePlate: '',
    vin: '',
    fuelType: '',
    transmissionType: '',
    vehicleType: '',
    engineCapacity: '',
    mileage: '',
    registrationDate: '',
    insuranceExpiry: '',
    lastMaintenance: '',
    nextMaintenanceDate: '',
    status: 'ACTIVE',
    ownerName: '',
    ownerEmail: '',
    deviceId: '',
    deviceSerialNumber: '',
    deviceModel: '',
    deviceVersion: '',
    lastLatitude: '',
    lastLongitude: '',
    hasGPS: false,
    hasAlarm: false,
    hasImmobilizer: false,
    hasCamera: false,
    tags: [],
    notes: ''
  });

  // 车辆状态选项
  const statuses = [
    { value: 'ACTIVE', label: '正常运行' },
    { value: 'INACTIVE', label: '未激活' },
    { value: 'MAINTENANCE', label: '维修保养中' },
    { value: 'STOLEN', label: '被盗' },
    { value: 'SOLD', label: '已出售' },
    { value: 'SCRAPPED', label: '已报废' }
  ];

  // 燃料类型选项
  const fuelTypes = [
    { value: 'GASOLINE', label: '汽油' },
    { value: 'DIESEL', label: '柴油' },
    { value: 'ELECTRIC', label: '电动' },
    { value: 'HYBRID', label: '混合动力' },
    { value: 'OTHER', label: '其他' }
  ];

  // 变速箱类型选项
  const transmissionTypes = [
    { value: 'MANUAL', label: '手动' },
    { value: 'AUTOMATIC', label: '自动' },
    { value: 'CVT', label: '无级变速' },
    { value: 'DCT', label: '双离合' },
    { value: 'OTHER', label: '其他' }
  ];

  // 车辆类型选项
  const vehicleTypes = [
    { value: 'SEDAN', label: '轿车' },
    { value: 'SUV', label: 'SUV' },
    { value: 'MPV', label: 'MPV' },
    { value: 'PICKUP', label: '皮卡' },
    { value: 'VAN', label: '面包车' },
    { value: 'SPORT', label: '跑车' },
    { value: 'TRUCK', label: '卡车' },
    { value: 'OTHER', label: '其他' }
  ];

  // 加载当前用户信息
  const loadCurrentUser = async () => {
    try {
      const response = await apiRequest.get('/api/auth/me');
      setCurrentUser(response.data);
    } catch (err) {
      console.error('Error loading current user:', err);
    }
  };

  // 加载车辆详情数据
  const loadVehicleDetail = async () => {
    setLoading(true);
    setError('');
    
    try {
      console.log(`Loading vehicle with ID: ${id}`);
      const response = await apiRequest.get(`/api/vehicles/${id}`);
      const vehicle = response.data;
      
      console.log('Vehicle data loaded successfully:', vehicle);
      
      // 格式化日期，确保正确显示
      const formatDate = (dateString) => {
        if (!dateString) return '';
        // 尝试处理ISO 8601格式的日期字符串
        if (typeof dateString === 'string' && dateString.includes('T')) {
          // 如果日期字符串已经包含时间部分，直接提取日期部分
          return dateString.split('T')[0];
        }
        const date = new Date(dateString);
        if (isNaN(date.getTime())) return '';
        return date.toISOString().split('T')[0]; // YYYY-MM-DD 格式
      };
      
      // 设置表单数据
      setFormData({
        brand: vehicle.brand || '',
        model: vehicle.model || '',
        color: vehicle.color || '',
        year: vehicle.year || '',
        licensePlate: vehicle.licensePlate || '',
        vin: vehicle.vin || '',
        fuelType: vehicle.fuelType || '',
        transmissionType: vehicle.transmissionType || '',
        vehicleType: vehicle.vehicleType || '',
        engineCapacity: vehicle.engineCapacity || '',
        mileage: vehicle.mileage || '',
        registrationDate: formatDate(vehicle.registrationDate),
        insuranceExpiry: formatDate(vehicle.insuranceExpiry),
        lastMaintenance: formatDate(vehicle.lastMaintenance),
        nextMaintenanceDate: formatDate(vehicle.nextMaintenanceDate),
        status: vehicle.status || 'ACTIVE',
        ownerName: vehicle.ownerName || '',
        ownerEmail: vehicle.ownerEmail || '',
        deviceId: vehicle.deviceId || '',
        deviceSerialNumber: vehicle.deviceSerialNumber || '',
        deviceModel: vehicle.deviceModel || '',
        deviceVersion: vehicle.deviceVersion || '',
        lastLatitude: vehicle.lastLatitude || '',
        lastLongitude: vehicle.lastLongitude || '',
        hasGPS: vehicle.hasGPS || false,
        hasAlarm: vehicle.hasAlarm || false,
        hasImmobilizer: vehicle.hasImmobilizer || false,
        hasCamera: vehicle.hasCamera || false,
        tags: vehicle.tags || [],
        notes: vehicle.notes || ''
      });
      
    } catch (err) {
      console.error('Error loading vehicle detail:', err);
      const errorMessage = err.response?.data?.error || 
                          err.message || 
                          '加载车辆详情失败';
      setError(`加载失败: ${errorMessage}`);
    } finally {
      setLoading(false);
    }
  };

  // 处理表单变更
  const handleChange = (e) => {
    const { name, value, type, checked } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: type === 'checkbox' ? checked : type === 'number' ? Number(value) : value
    }));
  };

  // 处理标签添加
  const handleKeyPress = (e) => {
    if (e.key === 'Enter' && tagInput.trim()) {
      const newTag = tagInput.trim();
      if (!formData.tags.includes(newTag)) {
        setFormData(prev => ({
          ...prev,
          tags: [...prev.tags, newTag]
        }));
      }
      setTagInput('');
    }
  };

  // 处理标签删除
  const handleTagDelete = (tagToRemove) => {
    setFormData(prev => ({
      ...prev,
      tags: prev.tags.filter(tag => tag !== tagToRemove)
    }));
  };

  // 提交表单
  const handleSubmit = async (e) => {
    e.preventDefault();
    setLoading(true);
    setError('');
    setSuccess('');
    
    try {
      // 为日期字段添加默认时间（12:00:00）和时区信息
      const prepareDateWithTime = (dateString) => {
        if (!dateString) return null;
        // 创建Date对象以获取正确的带时区的ISO格式
        const date = new Date(dateString);
        // 设置时间为中午12点
        date.setHours(12, 0, 0, 0);
        // 返回完整的带时区的ISO字符串
        return date.toISOString();
      };
      
      // 准备提交数据
      const submitData = {
        ...formData,
        // 添加时间部分到日期字段
        registrationDate: prepareDateWithTime(formData.registrationDate),
        insuranceExpiry: prepareDateWithTime(formData.insuranceExpiry),
        lastMaintenance: prepareDateWithTime(formData.lastMaintenance),
        nextMaintenanceDate: prepareDateWithTime(formData.nextMaintenanceDate),
        // 转换数字类型的字段
        year: formData.year ? Number(formData.year) : null,
        engineCapacity: formData.engineCapacity ? Number(formData.engineCapacity) : null,
        mileage: formData.mileage ? Number(formData.mileage) : null,
        lastLatitude: formData.lastLatitude ? Number(formData.lastLatitude) : null,
        lastLongitude: formData.lastLongitude ? Number(formData.lastLongitude) : null
      };
      
      console.log('Submitting vehicle update:', submitData);
        // 确保token被正确添加到请求头
        const token = localStorage.getItem('token');
        console.log('Using token for authorization:', token ? 'Yes' : 'No');
        
        // 创建一个自定义axios实例，确保包含正确的授权头
        const customRequest = axios.create({
          baseURL: '/vehicle-secure',
          headers: {
            'Content-Type': 'application/json',
            Authorization: token ? `Bearer ${token}` : ''
          }
        });
        const response = await customRequest.put(`/api/vehicles/${id}`, submitData);
      
      console.log('Vehicle updated successfully:', response.data);
      setSuccess('车辆信息更新成功！');
      
      // 3秒后重定向回详情页
      setTimeout(() => {
        navigate(`/vehicles/${id}`);
      }, 3000);
      
    } catch (err) {
      console.error('Error updating vehicle:', err);
      const errorMessage = err.response?.data?.error || 
                          err.message || 
                          '更新车辆信息失败';
      setError(`更新失败: ${errorMessage}`);
    } finally {
      setLoading(false);
    }
  };

  // 返回上一页
  const handleBack = () => {
    navigate(-1);
  };

  // 初始加载数据
  useEffect(() => {
    loadCurrentUser();
    loadVehicleDetail();
  }, [id]);

  if (loading && !formData.brand) {
    return (
      <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', minHeight: '80vh' }}>
        <CircularProgress size={60} />
      </Box>
    );
  }

  return (
    <Box p={3}>
      <Box sx={{ display: 'flex', alignItems: 'center', mb: 3 }}>
        <Button 
          startIcon={<ArrowBack />}
          onClick={handleBack}
          sx={{ mr: 2 }}
        >
          返回
        </Button>
        <Typography variant="h4" gutterBottom>
          编辑车辆信息
        </Typography>
      </Box>

      <Grid container spacing={3}>
        <Grid item xs={12} md={8}>
          <Paper elevation={3} sx={{ p: 3 }}>
            {error && (
              <Alert severity="error" sx={{ mb: 2 }}>
                {error}
              </Alert>
            )}
            
            {success && (
              <Alert severity="success" sx={{ mb: 2 }}>
                {success}
              </Alert>
            )}

            <form onSubmit={handleSubmit}>
              {/* 基本信息 */}
              <Typography variant="h6" gutterBottom sx={{ mt: 2, mb: 1 }}>
                基本信息
              </Typography>
              <Grid container spacing={3}>
                <Grid item xs={12} sm={6}>
                  <TextField
                    fullWidth
                    label="品牌"
                    name="brand"
                    value={formData.brand}
                    onChange={handleChange}
                    required
                    variant="outlined"
                  />
                </Grid>
                
                <Grid item xs={12} sm={6}>
                  <TextField
                    fullWidth
                    label="型号"
                    name="model"
                    value={formData.model}
                    onChange={handleChange}
                    required
                    variant="outlined"
                  />
                </Grid>
                
                <Grid item xs={12} sm={6}>
                  <TextField
                    fullWidth
                    label="颜色"
                    name="color"
                    value={formData.color}
                    onChange={handleChange}
                    variant="outlined"
                  />
                </Grid>
                
                <Grid item xs={12} sm={6}>
                  <TextField
                    fullWidth
                    label="生产年份"
                    name="year"
                    type="number"
                    value={formData.year}
                    onChange={handleChange}
                    required
                    variant="outlined"
                    inputProps={{ min: 1900, max: new Date().getFullYear() + 1 }}
                  />
                </Grid>
                
                <Grid item xs={12} sm={6}>
                  <TextField
                    fullWidth
                    label="车牌号码"
                    name="licensePlate"
                    value={formData.licensePlate}
                    onChange={handleChange}
                    required
                    variant="outlined"
                  />
                </Grid>
                
                <Grid item xs={12} sm={6}>
                  <TextField
                    fullWidth
                    label="车辆识别码 (VIN)"
                    name="vin"
                    value={formData.vin}
                    onChange={handleChange}
                    required
                    variant="outlined"
                    inputProps={{ maxLength: 17 }}
                  />
                </Grid>
                
                <Grid item xs={12} sm={4}>
                  <FormControl fullWidth>
                    <InputLabel>燃料类型</InputLabel>
                    <Select
                      name="fuelType"
                      value={formData.fuelType}
                      onChange={handleChange}
                      label="燃料类型"
                    >
                      {fuelTypes.map(type => (
                        <MenuItem key={type.value} value={type.value}>{type.label}</MenuItem>
                      ))}
                    </Select>
                  </FormControl>
                </Grid>
                
                <Grid item xs={12} sm={4}>
                  <FormControl fullWidth>
                    <InputLabel>变速箱类型</InputLabel>
                    <Select
                      name="transmissionType"
                      value={formData.transmissionType}
                      onChange={handleChange}
                      label="变速箱类型"
                    >
                      {transmissionTypes.map(type => (
                        <MenuItem key={type.value} value={type.value}>{type.label}</MenuItem>
                      ))}
                    </Select>
                  </FormControl>
                </Grid>
                
                <Grid item xs={12} sm={4}>
                  <FormControl fullWidth>
                    <InputLabel>车辆类型</InputLabel>
                    <Select
                      name="vehicleType"
                      value={formData.vehicleType}
                      onChange={handleChange}
                      label="车辆类型"
                    >
                      {vehicleTypes.map(type => (
                        <MenuItem key={type.value} value={type.value}>{type.label}</MenuItem>
                      ))}
                    </Select>
                  </FormControl>
                </Grid>
                
                <Grid item xs={12} sm={6}>
                  <TextField
                    fullWidth
                    label="发动机排量 (升)"
                    name="engineCapacity"
                    type="number"
                    value={formData.engineCapacity}
                    onChange={handleChange}
                    variant="outlined"
                    inputProps={{ min: 0, max: 10, step: 0.1 }}
                  />
                </Grid>
                
                <Grid item xs={12} sm={6}>
                  <TextField
                    fullWidth
                    label="当前里程 (公里)"
                    name="mileage"
                    type="number"
                    value={formData.mileage}
                    onChange={handleChange}
                    variant="outlined"
                    inputProps={{ min: 0 }}
                  />
                </Grid>
              </Grid>

              {/* 状态信息 */}
              <Typography variant="h6" gutterBottom sx={{ mt: 3, mb: 1 }}>
                状态信息
              </Typography>
              <Grid container spacing={3}>
                <Grid item xs={12} sm={6}>
                  <TextField
                    fullWidth
                    label="注册日期"
                    name="registrationDate"
                    type="date"
                    value={formData.registrationDate}
                    onChange={handleChange}
                    required
                    variant="outlined"
                    InputLabelProps={{ shrink: true }}
                  />
                </Grid>
                
                <Grid item xs={12} sm={6}>
                  <TextField
                    fullWidth
                    label="保险到期日"
                    name="insuranceExpiry"
                    type="date"
                    value={formData.insuranceExpiry}
                    onChange={handleChange}
                    required
                    variant="outlined"
                    InputLabelProps={{ shrink: true }}
                  />
                </Grid>
                
                <Grid item xs={12} sm={6}>
                  <TextField
                    fullWidth
                    label="最后保养日期"
                    name="lastMaintenance"
                    type="date"
                    value={formData.lastMaintenance}
                    onChange={handleChange}
                    required
                    variant="outlined"
                    InputLabelProps={{ shrink: true }}
                  />
                </Grid>
                
                <Grid item xs={12} sm={6}>
                  <TextField
                    fullWidth
                    label="下次保养日期"
                    name="nextMaintenanceDate"
                    type="date"
                    value={formData.nextMaintenanceDate}
                    onChange={handleChange}
                    variant="outlined"
                    InputLabelProps={{ shrink: true }}
                  />
                </Grid>
                
                <Grid item xs={12} sm={6}>
                  <FormControl fullWidth>
                    <InputLabel>车辆状态</InputLabel>
                    <Select
                      name="status"
                      value={formData.status}
                      onChange={handleChange}
                      label="车辆状态"
                    >
                      {statuses.map(status => (
                        <MenuItem key={status.value} value={status.value}>{status.label}</MenuItem>
                      ))}
                    </Select>
                  </FormControl>
                </Grid>
              </Grid>

              {/* 车主信息（已自动获取当前登录用户信息） */}
              <Typography variant="h6" gutterBottom sx={{ mt: 3, mb: 1 }}>
                车主信息
              </Typography>
              <Grid container spacing={3}>
                <Grid item xs={12} sm={6}>
                  <TextField
                    fullWidth
                    label="车主姓名"
                    name="ownerName"
                    value={formData.ownerName}
                    onChange={handleChange}
                    disabled
                    variant="outlined"
                  />
                </Grid>
                
                <Grid item xs={12} sm={6}>
                  <TextField
                    fullWidth
                    label="邮箱地址"
                    name="ownerEmail"
                    value={formData.ownerEmail}
                    onChange={handleChange}
                    disabled
                    variant="outlined"
                  />
                </Grid>
              </Grid>
              <Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}>
                系统自动使用当前登录用户作为车主，如需修改请联系管理员。
              </Typography>

              {/* 设备信息 */}
              <Typography variant="h6" gutterBottom sx={{ mt: 3, mb: 1 }}>
                设备信息
              </Typography>
              <Grid container spacing={3}>
                <Grid item xs={12} sm={6}>
                  <TextField
                    fullWidth
                    label="设备ID"
                    name="deviceId"
                    value={formData.deviceId}
                    onChange={handleChange}
                    variant="outlined"
                  />
                </Grid>
                
                <Grid item xs={12} sm={6}>
                  <TextField
                    fullWidth
                    label="设备序列号"
                    name="deviceSerialNumber"
                    value={formData.deviceSerialNumber}
                    onChange={handleChange}
                    variant="outlined"
                  />
                </Grid>
                
                <Grid item xs={12} sm={6}>
                  <TextField
                    fullWidth
                    label="设备型号"
                    name="deviceModel"
                    value={formData.deviceModel}
                    onChange={handleChange}
                    variant="outlined"
                  />
                </Grid>
                
                <Grid item xs={12} sm={6}>
                  <TextField
                    fullWidth
                    label="设备版本"
                    name="deviceVersion"
                    value={formData.deviceVersion}
                    onChange={handleChange}
                    variant="outlined"
                  />
                </Grid>
              </Grid>

              {/* 位置信息 */}
              <Typography variant="h6" gutterBottom sx={{ mt: 3, mb: 1 }}>
                位置信息
              </Typography>
              <Grid container spacing={3}>
                <Grid item xs={12} sm={6}>
                  <TextField
                    fullWidth
                    label="纬度"
                    name="lastLatitude"
                    type="number"
                    value={formData.lastLatitude}
                    onChange={handleChange}
                    variant="outlined"
                    inputProps={{ step: 0.0001 }}
                  />
                </Grid>
                
                <Grid item xs={12} sm={6}>
                  <TextField
                    fullWidth
                    label="经度"
                    name="lastLongitude"
                    type="number"
                    value={formData.lastLongitude}
                    onChange={handleChange}
                    variant="outlined"
                    inputProps={{ step: 0.0001 }}
                  />
                </Grid>
              </Grid>

              {/* 安全设备 */}
              <Typography variant="h6" gutterBottom sx={{ mt: 3, mb: 1 }}>
                安全设备
              </Typography>
              <FormGroup row>
                <FormControlLabel
                  control={<Checkbox checked={formData.hasGPS} onChange={handleChange} name="hasGPS" />}
                  label="GPS定位"
                />
                <FormControlLabel
                  control={<Checkbox checked={formData.hasAlarm} onChange={handleChange} name="hasAlarm" />}
                  label="报警器"
                />
                <FormControlLabel
                  control={<Checkbox checked={formData.hasImmobilizer} onChange={handleChange} name="hasImmobilizer" />}
                  label="防盗器"
                />
                <FormControlLabel
                  control={<Checkbox checked={formData.hasCamera} onChange={handleChange} name="hasCamera" />}
                  label="摄像头"
                />
              </FormGroup>

              {/* 标签和备注 */}
              <Typography variant="h6" gutterBottom sx={{ mt: 3, mb: 1 }}>
                标签和备注
              </Typography>
              <Grid container spacing={3}>
                <Grid item xs={12}>
                  <TextField
                    fullWidth
                    label="添加标签"
                    value={tagInput}
                    onChange={(e) => setTagInput(e.target.value)}
                    onKeyPress={handleKeyPress}
                    variant="outlined"
                    helperText="输入标签后按回车添加"
                  />
                  <Box sx={{ mt: 1 }}>
                    {formData.tags.map((tag, index) => (
                      <Chip
                        key={index}
                        label={tag}
                        onDelete={() => handleTagDelete(tag)}
                        color="primary"
                        variant="outlined"
                        sx={{ mr: 1, mb: 1 }}
                      />
                    ))}
                  </Box>
                </Grid>
                
                <Grid item xs={12}>
                  <TextField
                    fullWidth
                    label="备注"
                    name="notes"
                    value={formData.notes}
                    onChange={handleChange}
                    variant="outlined"
                    multiline
                    rows={3}
                  />
                </Grid>
              </Grid>

              <Grid item xs={12} sx={{ mt: 3 }}>
                <Button
                  type="submit"
                  variant="contained"
                  color="primary"
                  startIcon={<Save />}
                  disabled={loading}
                  sx={{ mr: 2 }}
                >
                  {loading ? '保存中...' : '保存更改'}
                </Button>
                <Button
                  variant="outlined"
                  onClick={handleBack}
                  disabled={loading}
                >
                  取消
                </Button>
              </Grid>
            </form>
          </Paper>
        </Grid>
        
        {/* 右侧信息 */}
        <Grid item xs={12} md={4}>
          <Paper elevation={3} sx={{ p: 3, mb: 3 }}>
            <Typography variant="h6" gutterBottom>
              编辑提示
            </Typography>
            <Box sx={{ mb: 2 }}>
              <Typography variant="body2" color="text.secondary" gutterBottom>
                • 请确保所有必填项已正确填写
              </Typography>
              <Typography variant="body2" color="text.secondary" gutterBottom>
                • VIN码必须为17位字母数字组合
              </Typography>
              <Typography variant="body2" color="text.secondary" gutterBottom>
                • 修改后的信息将立即生效
              </Typography>
              <Typography variant="body2" color="text.secondary" gutterBottom>
                • 如需更改车主信息，请联系管理员
              </Typography>
            </Box>
          </Paper>
          
          <Paper elevation={3} sx={{ p: 3 }}>
            <Typography variant="h6" gutterBottom>
              车辆ID
            </Typography>
            <Typography variant="body2" color="text.secondary">
              {id}
            </Typography>
          </Paper>
        </Grid>
      </Grid>
    </Box>
  );
};

export default VehicleEdit;